<template>
	<view class="container">
		<!-- 导航栏 -->
		<nav-bar></nav-bar>
		<tech-nav-bar title="实名认证" :currentPage="'/pages/technician/verification'"></tech-nav-bar>

		<!-- 表单区域 -->
		<view class="form-section">
			<!-- 姓名输入 -->
			<view class="form-item">
				<text class="label">姓名</text>
				<input class="input" type="text" v-model="formData.name" placeholder="请输入姓名" />
			</view>

			<!-- 身份证号输入 -->
			<view class="form-item">
				<text class="label">身份证号</text>
				<input class="input" type="idcard" v-model="formData.idNumber" placeholder="请输入身份证号" maxlength="18" />
			</view>
		</view>

		<!-- 拍照上传区域 -->
		<view class="photo-section">
			<text class="photo-title">
				<text class="required">*</text>
				请拍摄本人实拍照片
			</text>

			<!-- 示例照片 -->
			<view class="example-photo">
				<image class="example-img" src="/static/box.png" mode="aspectFit"></image>
				<view class="requirements">
					<text>拍摄要求</text>
					<text>正面、免冠、素颜、清晰</text>
					<text>光线良好、背景整洁</text>
				</view>
			</view>

			<!-- 上传区域 -->
			<view class="upload-area" @tap="takePhoto">
				<image v-if="formData.photo" :src="formData.photo" mode="aspectFill" class="uploaded-photo"></image>
				<view v-else class="upload-placeholder">
					<text class="upload-icon">+</text>
				</view>
			</view>
		</view>

		<view style="padding: 30rpx;">
			<button @click="commit">提交</button>
		</view>

		<!-- 说明区域 -->
		<view class="info-section">
			<view class="info-title">
				<text class="question-icon">?</text>
				<text>什么是实名认证？</text>
			</view>
			<view class="info-content">
				实名认证是指通过姓名、身份证号和实拍照片，核实认证人身份真实性的一种手段。上单平台将严格保护您的隐私，您上传的身份信息仅供平台认证使用，不会泄露给任何第三方。
			</view>
			<view class="info-title">
				<text class="question-icon">?</text>
				<text>为什么要进行实名认证？</text>
			</view>
			<view class="info-content">
				上单作为到位旗下的上门服务人员就业接单平台，需要对服务人员的身份进行核实，以确保用户的安全。更重要的是，平台需要维护服务人员的权益，避免不法分子伪造、冒用他人身份信息，对其他服务人员的从业经历及名誉造成影响。
			</view>
		</view>
	</view>
</template>

<script>
	import TechNavBar from '@/components/tech-nav-bar.vue'
	import NavBar from '@/components/nav-bar/nav-bar.vue'
	export default {
		components: {
			TechNavBar,
			NavBar
		},
		data() {
			return {
				formData: {
					name: '',
					idNumber: '',
					photo: '',
					id: null,
					fileId: null,
				}
			}
		},
		created() {
			this.getUserInfo()
		},
		methods: {
			validateIdCard() {
				if (!this.formData.idNumber) {
					return '请输入身份证号码';
				}
				if (this.formData.idNumber.length !== 18) {
					return '身份证号码长度应为18位';
				}
				const reg = /^\d{17}[\dXx]$/;
				if (!reg.test(this.formData.idNumber)) {
					return '格式错误：前17位应为数字，最后一位为数字或X';
				}
				const birthDateStr = this.formData.idNumber.substring(6, 14);
				const year = parseInt(birthDateStr.substring(0, 4));
				const month = parseInt(birthDateStr.substring(4, 6)) - 1; // 月份0-11
				const day = parseInt(birthDateStr.substring(6, 8));
				// 创建日期对象进行验证
				const birthDate = new Date(year, month, day);
				// 验证日期是否有效
				if (birthDate.getFullYear() !== year || birthDate.getMonth() !== month || birthDate.getDate() !== day) {
					return '出生日期无效';
				}
				// 验证年龄范围（0-150岁）
				const currentYear = new Date().getFullYear();
				if (year < currentYear - 150 || year > currentYear) {
					return '出生年份超出有效范围';
				}
				// 校验码权重系数
				const factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
				// 校验码对应表
				const checkCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
				let sum = 0;
				for (let i = 0; i < 17; i++) {
					sum += parseInt(this.formData.idNumber.charAt(i)) * factors[i];
				}
				const mod = sum % 11;
				const checkCode = checkCodes[mod];
				if (this.formData.idNumber.charAt(17).toUpperCase() !== checkCode) {
					return '校验码错误，正确应为: ' + checkCode;
				}
			},
			validateName() {
				const re = /^[\u4e00-\u9fa5]{2,20}$/;
				return re.test(this.formData.name) ? '' : '姓名需为2-20个中文字符';
			},
			async commit() {
				const nameErr = this.validateName();
				if (nameErr) {
					uni.showModal({ title: '提示', content: nameErr + '\n请输入正确的姓名', showCancel: false });
					return;
				}
				if (!this.formData.name) {
					uni.showToast({
						title: '请输入姓名',
						icon: 'error',
						duration: 2000
					})
					return
				}
				const idRes = this.validateIdCard()
				if (idRes) {
					uni.showModal({
						title: '提示',
						content: idRes + '\n请输入正确的身份证号',
						showCancel: false
					})
					return
				}
				if (!this.formData.photo) {
					uni.showToast({
						title: '请上传照片',
						icon: 'error',
						duration: 2000
					})
					return
				}
				uni.showLoading({ title: '提交中...' })
				try {
					const that = this;
					uni.request({
						url: `${uni.$config.baseUrl}/technician/technician`,
						method: 'PUT',
						data: {
							name: that.formData.name,
							idNumber: that.formData.idNumber,
							id: that.formData.id,
							fileId: that.formData.fileId,
						},
						success(res) {
							uni.hideLoading();
							if (res.data && res.data.code === 200) {
								uni.showToast({ title: '提交成功', icon: 'success' })
								// 更新本地缓存
								let userInfo = uni.getStorageSync('userInfo') || {}
								userInfo.realName = that.formData.name
								userInfo.idNumber = that.formData.idNumber
								uni.setStorageSync('userInfo', userInfo)
								// 同步上一页显示
								const pages = getCurrentPages();
								if (pages.length > 1) {
									const prev = pages[pages.length - 2];
									if (prev.$vm) {
										prev.$vm.realName = that.formData.name;
										prev.$vm.isVerified = true;
									}
								}
								setTimeout(() => {
									uni.navigateBack()
								}, 800)
							} else {
								uni.showToast({ title: res.data.msg || '提交失败', icon: 'none' })
							}
						},
						fail() {
							uni.hideLoading();
							uni.showToast({ title: '网络错误', icon: 'none' })
						}
					});
				} catch (e) {
					uni.hideLoading();
					uni.showToast({ title: '提交失败', icon: 'none' });
				}
			},
			async getUserInfo() {
				const userInfo = await uni.getStorageSync('userInfo')
				const result = await uni.request({
					url: `${uni.$config.baseUrl}/technician/technician/${userInfo.techId}`,
					method: 'GET',
				})
				if (result.data.code === 200 && result.data.data) {
					this.formData.name = result.data.data.name
					this.formData.idNumber = result.data.data.idNumber
					this.formData.id = result.data.data.id
					this.formData.fileId = result.data.data.fileId
					this.formData.photo = result.data.data.url
				}
			},
			// 拍照或选择照片
			takePhoto() {
				// 直接调用相机
				uni.chooseImage({
					count: 1, // 只能选择一张图片
					sizeType: ['compressed'], // 压缩图片
					sourceType: ['camera'], // 只允许使用相机拍摄
					success: (res) => {
						try {
							// 获取图片信息
							uni.getImageInfo({
								src: res.tempFilePaths[0],
								success: (image) => {
									// 检查图片大小
									if (image.width < 200 || image.height < 200) {
										uni.showToast({
											title: '图片分辨率太低，请重新拍摄',
											icon: 'none'
										})
										return
									}
									// 检查图片大小（文件大小）
									uni.getFileInfo({
										filePath: res.tempFilePaths[0],
										success: (file) => {
											const maxSize = 10 * 1024 * 1024 // 最大10MB
											if (file.size > maxSize) {
												uni.showToast({
													title: '图片大小不能超过10MB',
													icon: 'none'
												})
												return
											}
											this.formData.photo = res.tempFilePaths[0]
											uni.showLoading({
												title: '上传中',
												mask: true
											})
											uni.uploadFile({
												url: `${uni.$config.baseUrl}/common/upload`,
												filePath: res.tempFilePaths[0],
												name: 'file',
												formData: {},
												success: (uploadRes) => {
													if (uploadRes
														.statusCode === 200
														) {
														try {
															const
																responseData =
																JSON.parse(
																	uploadRes
																	.data);
															if (responseData
																.code ===
																200) {
																this.formData
																	.fileId =
																	responseData
																	.id;
															} else {
																uni.showToast({
																	title: responseData
																		.message ||
																		'上传失败',
																	icon: 'none'
																});
															}
														} catch (e) {
															uni.showToast({
																title: '解析响应失败',
																icon: 'none'
															});
														}
													} else {
														uni.showToast({
															title: `上传失败：${uploadRes.statusCode}`,
															icon: 'none'
														});
													}
													uni.hideLoading()
												},
												fail: (err) => {
													uni.showToast({
														title: '上传失败，请检查网络',
														icon: 'none'
													});
													uni.hideLoading()
												}
											});
										}
									})
								},
								fail: (err) => {
									uni.showToast({
										title: '获取图片信息失败',
										icon: 'none'
									})
								}
							})
						} catch (err) {
							uni.showToast({
								title: err,
								icon: 'error',
								duration: 3000
							})
							uni.hideLoading()
						}
					},
					fail: (err) => {
						// 判断是否是用户取消了操作
						if (err.errMsg.indexOf('cancel') !== -1) {
							uni.showToast({
								title: '已取消拍照',
								icon: 'none'
							})
						} else {
							// 检查是否是权限问题
							if (err.errMsg.indexOf('permission') !== -1) {
								uni.showModal({
									title: '提示',
									content: '需要相机权限才能完成实名认证，请在系统设置中开启相机权限',
									confirmText: '去设置',
									success: (res) => {
										if (res.confirm) {
											// 打开系统设置
											uni.openSetting({
												success: (settingRes) => {
													console.log('设置结果：', settingRes)
												}
											})
										}
									}
								})
							} else {
								uni.showToast({
									title: '拍照失败，请重试',
									icon: 'none'
								})
							}
						}
					}
				})
			},
			// 提交认证
			submitVerification() {
				// 表单验证
				if (!this.formData.name) {
					uni.showToast({
						title: '请输入姓名',
						icon: 'none'
					})
					return
				}
				if (!this.formData.idNumber) {
					uni.showToast({
						title: '请输入身份证号',
						icon: 'none'
					})
					return
				}
				if (!this.formData.photo) {
					uni.showToast({
						title: '请上传实拍照片',
						icon: 'none'
					})
					return
				}

				// TODO: 调用认证接口
				uni.showLoading({
					title: '提交中...'
				})

				// 模拟接口调用
				setTimeout(() => {
					uni.hideLoading()
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					})
					// 返回上一页
					uni.navigateBack()
				}, 2000)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		min-height: 100vh;
		background: #F5F5F5;
		padding-bottom: 40rpx;
	}

	.form-section {
		background: #FFFFFF;
		padding: 0 30rpx;
		margin-bottom: 20rpx;
	}

	.form-item {
		display: flex;
		align-items: center;
		padding: 30rpx 0;
		border-bottom: 1px solid #EEEEEE;

		&:last-child {
			border-bottom: none;
		}

		.label {
			width: 140rpx;
			font-size: 30rpx;
			color: #333333;
		}

		.input {
			flex: 1;
			font-size: 30rpx;
			color: #333333;
		}
	}

	.photo-section {
		background: #FFFFFF;
		padding: 30rpx;
		margin-bottom: 20rpx;
	}

	.photo-title {
		font-size: 30rpx;
		color: #333333;
		margin-bottom: 30rpx;

		.required {
			color: #FF0000;
			margin-right: 10rpx;
		}
	}

	.example-photo {
		display: flex;
		align-items: center;
		background: #F8F8F8;
		padding: 20rpx;
		border-radius: 8rpx;
		margin-bottom: 30rpx;

		.example-img {
			width: 160rpx;
			height: 160rpx;
			margin-right: 30rpx;
		}

		.requirements {
			flex: 1;

			text {
				display: block;
				font-size: 26rpx;
				color: #666666;
				line-height: 1.8;

				&:first-child {
					color: #333333;
					font-size: 28rpx;
					margin-bottom: 10rpx;
				}
			}
		}
	}

	.upload-area {
		width: 240rpx;
		height: 240rpx;
		margin: 0 auto;

		.upload-placeholder {
			width: 100%;
			height: 100%;
			background: #F8F8F8;
			border: 2rpx dashed #DDDDDD;
			border-radius: 8rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.upload-icon {
				font-size: 80rpx;
				color: #999999;
			}
		}

		.uploaded-photo {
			width: 100%;
			height: 100%;
			border-radius: 8rpx;
		}
	}

	.info-section {
		background: #FFFFFF;
		padding: 30rpx;
	}

	.info-title {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;

		.question-icon {
			width: 36rpx;
			height: 36rpx;
			line-height: 36rpx;
			text-align: center;
			background: #2B85E4;
			color: #FFFFFF;
			border-radius: 50%;
			font-size: 24rpx;
			margin-right: 10rpx;
		}

		text {
			font-size: 30rpx;
			color: #333333;
			font-weight: bold;
		}
	}

	.info-content {
		font-size: 28rpx;
		color: #666666;
		line-height: 1.6;
		margin-bottom: 100rpx;
	}
</style>